using System;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace MongoDynamic.Tests.Driver
{
    public class IdGenerator : IIdGenerator
    {
        private const string LastId = "LastId";
        private const string Id = "_id";

        public object GenerateId(object container, object document)
        {
            var coll = (MongoCollection)container;
            var idColl = coll.Database.GetCollection("MongoKeys");

            var docName = coll.Name;
            var f = idColl.FindAndModify(Query.EQ(Id, docName), SortBy.Null, Update.Inc(LastId, 1), true, true);
            return f.ModifiedDocument[LastId].AsInt32;
        }

        public bool IsEmpty(object id)
        {
            return id == null || (id is int) && Convert.ToInt32(id) == 0;
        }
    }
}